package it.demosms.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * 短信工具类
 *
 * @author 季鑫利
 */
@Component
@PropertySource(value = "classpath:sms.properties")
public class SmsUtil {
    /**
     * 日志
     */
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 阿里云用户accessKeyId
     */
    @Value("${accessKeyId}")
    private String accessKeyId;

    /**
     * 阿里云用户accessKeySecret
     */
    @Value("${accessKeySecret}")
    private String accessKeySecret;

    public CommonResponse sendSms(String phone, String smsCode, String param) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        //接收手机
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", "畅购");
        //模板code
        request.putQueryParameter("TemplateCode", smsCode);
        //验证码发送模板
        request.putQueryParameter("TemplateParam", param);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response;
        } catch (ClientException e) {
            e.printStackTrace();
            log.error("【响应失败】---->" + e.getMessage());
            return null;
        }
    }
}
